package com.lin.fengxiu.api.v1;

import com.lin.fengxiu.core.interceptors.ScopeLevel;
import com.lin.fengxiu.lib.LinWxNotify;
import com.lin.fengxiu.service.WxPaymentNotifyService;
import com.lin.fengxiu.service.WxPaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Positive;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * @ClassName PaymentController
 * @Description TODO 支付 API
 * @Author wushaopei
 * @Date 2021/4/10 17:55
 * @Version 1.0
 */
@RequestMapping("payment")
@RestController
@Validated
public class PaymentController {

    @Autowired
    private WxPaymentService wxPaymentService;

    @Autowired
    private WxPaymentNotifyService wxPaymentNotifyService;

    /**
     * @Description TODO 预支付接口，返回微信支付签名
     * @param oid 订单id
     * @return  Map<String,String> 返回的微信签名，使用key-value键值对方式处理
     */
    @ScopeLevel
    @PostMapping("/pay/order/{id}")
    public Map<String,String> preWxOrder(@PathVariable(name = "id")@Positive Long oid){
        // 调用preOrder返回支付签名
        Map<String,String> miniPayParam = this.wxPaymentService.preOrder(oid);
        return miniPayParam;
    }

    /**
     * @Description TODO 支付回調接口
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/wx/notify")
    public String payCallback(HttpServletRequest request,
                              HttpServletResponse response){
        InputStream s;
        try {
            // 读取支付回调结果
            s = request.getInputStream();
        }catch (IOException e){
            // 处理支付结果失败，返回 false
            e.printStackTrace();
            return LinWxNotify.fail();
        }
        String xml;
        xml = LinWxNotify.readNotify(s);
        try {
            // 调用支付结果校验函数
            this.wxPaymentNotifyService.processPayNotify(xml);
        }catch (Exception e){
            return LinWxNotify.fail();
        }
        return LinWxNotify.success();
    }
}
